package Rservetest.Rservetest;

import java.util.Properties;

import org.math.R.RserveSession;
import org.math.R.RserverConf;
import org.math.R.Rsession;
import org.math.R.Rsession.RException;

public class DealModelFit {
	public static void main(String args[]) throws RException {
		//远程R服务器应该有权限读取数据库!!!!并且安装好GDAL,proj4和GEOS开源GIS库，有权限安装R包
		//远程R服务器运行Rserve::Rserve(args=' --no-restore --no-save --slave --RS-enable-remote',quote=F)
		RserverConf rconf = new RserverConf("10.10.10.56", 6311, "", "", new Properties());		
		Rsession s = null;
		s = RserveSession.newRemoteInstance(System.out, rconf);
		s.setCRANRepository("https://mirrors.tuna.tsinghua.edu.cn/CRAN/"); //设置安装镜像
		s.voidEval("devtools::install_git('https://git.oschina.net/seifer_08ms/gwr.avm.git')"); //安装package，（不必每次都安装，仅为测试）
		s.voidEval("library(gwr.avm)");   //加载package
		s.voidEval("install.dependencies()"); //安装依赖
		//建立数据库连接		
//		s.voidEval("con<-dbconnect(user='wangcl',"+
//				"password='wangchenliang_CR_2017',"+
//				"host='10.11.10.34',dbname='cityre_beijing',port=3307)"); 
		s.voidEval("con<-dbconnect(user ='datatestuser',"+
	               "password ='cityhousedata_db_2017',"+
	               "dbname = 'cityre_beijing',"+
	               "host = '10.11.10.34',port = 3307 )");
		//	    # 读取基础数据
		s.voidEval("tabln.vec<-loadData(con=con,month_offset = -2)");
		s.voidEval("tabln.vec$ha_info.sp<-tabln.vec$ha_info.sp%>%remove.spatial.outlier(city_code='bj')");
		//	    # 建立poi相关信息
		s.voidEval("poi.data.list<-getpoi.ras(con=con,tabln.vec = tabln.vec)");
		//	    # 取出得到POI信息的小区信息
		s.voidEval("tabln.vec$ha_info.sp<-poi.data.list$ha_info.sp");
		//	    # 准备建模数据
		s.voidEval("data.sets.all<-avm.data.train(tabln.vec,proptype = '11')");
		//	    # 取出房源交易数据,并排除一些字段
		s.voidEval("data.deal.sale<-read.deal(con = con,year = 2017,month = 7,proptype = 11,"+
				"var.except = c('ID','offertm','bldgcode','bheight','floor','lr','strucode',"+
				"'facecode','int_deco','propRT','dealcode'))");
		//	    # 关联交易与小区
		s.voidEval("data.deal.sale.ha<-merge(data.deal.sale,data.sets.all,by='ha_code')");
		//	    # 分割训练集和测试集
		s.voidEval("data.sets<-data.split(data =data.deal.sale.ha,train.rate = 0.75)");
		//	    # 房源建模时的排除变量
		s.voidEval("var.except.deal<-'-ID-offertm-unitprice-proptype-bldgcode-bheight-floor-lr-strucode-facecode-int_deco-propRT-dealcode'");
		//	    # 建模, 模拟房源房价
		s.voidEval("avm.models<-avm.fit(data.train = data.sets$train,"
				+ "dependentY = 'unitprice',"
				+ "ntree = 500,nround = 1000,"+
				"independentX = paste0('~.-yearmonth-ymid-ha_code-"
				+ "volume_rate-greening_rate',"+
				"'-x_-y_-saleprice-rentprice-unitprice',"+
				"'-rentbldgarea-salebldgarea-bldg_type-bldg_code',"+
				"var.except.deal),remove.dup=F)");
		//	    # 测试集预测
		s.voidEval("pred.test.data<-avm.pred(train.models=avm.models,newdata=data.sets$test%>%na.omit(),testing = T,remove.dup=F)");
		//	    # sapply(pred.test.data$pred%>%head,exp)
		s.voidEval("pred.test.data$rmse");
		s.voidEval("pred.test.data$mae");
		//	    # 保存路径，默认为'./models.avm'
		s.voidEval("model.path<-model.store.path('/tmp/avm')");
		//	    # 模型保存
		s.voidEval("avm.model.store(city_code='bj',avm.models = avm.models,"+
				"yearmonth = '2017-7',proptype = '11',dependentY = 'unitprice_sale')");

		//	    # 保存相关数据
		s.voidEval("saveRDS(tabln.vec,file.path(model.path,paste('bj','2017-7','tab.rds',sep='_')))");
		s.voidEval("saveRDS(poi.data.list,file.path(model.path,paste('bj','2017-7','poi.rds',sep='_')))");
		s.close();
	}
}